import axios from 'axios'
import { Message } from '@arco-design/web-vue'
import bus from "@/views/videoLabel/tools/bus";
const http = axios.create({
  baseURL: '/',
  timeout: 1000 * 60 * 30
})
const defaultMsg = '系统开小差，请稍后重试'
http.interceptors.request.use(
  config => {
    if(config.headers){
      config.headers['accessToken'] = window.localStorage.accessToken;
      config.headers['Content-Type'] = "application/json";
    }
    return config
  },
  error => {
    Message.clear()
    Message.error(error.msg || defaultMsg)
    return Promise.reject(error)
  }
)

http.interceptors.response.use(
  res => {
    const resData = res.data || {}
    const { code, data, msg } = resData
    if (code === 0) return data;
    if (code === undefined || code === -1) return resData; // 上传、下载文件的接口如果访问正常会直接返回文件数据，不会有code值
    Message.clear();
    handleError(code, msg);
    return Promise.reject(resData);
  },
  error => {
    Message.clear()
    Message.error(error.msg || defaultMsg)
    return Promise.reject(error)
  }
)
// 暂时只覆盖了如下部分的code值，可能会有遗漏
function handleError(code: number, msg: string) {
  switch (code) {
    case 503:
      Message.error("账户已被冻结");
      break;
    case 501:
      window.location.href = `${location.origin}/#!/login`;
      Message.error(msg);
      break;
    case 1301:
      Message.error(msg);
      bus.emit("Video.setLoading", false);
      break;
    default:
      Message.error(msg);
      break;
  }
}
export default http;
